import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class UdpEchoServer {
    private DatagramSocket socket = null;

    //绑定一个端口，不一定能成功
    public UdpEchoServer(int port) throws SocketException {
        //构造 socket的同时，指定绑定的端口
        socket = new DatagramSocket(port);
    }

    //启动服务器的主逻辑
    public void start() throws IOException {
        System.out.println("服务器启动！");
        while(true){
            //每次循环，都要做三件事
            // 1. 读取请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4090],4090);
            socket.receive(requestPacket);
            //为了方便处理这个请求，把数据包转换成 String
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());

            // 2. 根据请求，计算响应
            String response = process(request);

            // 3. 把响应的结果发送回客户端
            //根据 response 的字符串，构造一个 DatagramPacket
            // 此处构造响应时，需要指定这个包要发给谁
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(), response.getBytes().length,
                    requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s : %d] 请求：%s, 响应：%s\n",requestPacket.getAddress().toString(),
                    requestPacket.getPort(), request, response);
        }
    }

    //这是个 回显程序，请求啥，返回啥
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException{
        UdpEchoServer udpEchoServer = new UdpEchoServer(1000);
        udpEchoServer.start();
    }




}
